<?php
namespace App\Common\Lib\Com\RabbitMQ\_Channel;

use App\Common as com;
use App\Common\Lib\Com\RabbitMQ\_Channel\_Exchange as name_Exchange;
use App\Common\Lib\Com\RabbitMQ as nameRabbitMQ;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * @property nameRabbitMQ\DataStore $dataStore
 */
class _Exchange extends com\Cla\ClaBase\CommonOfId\Client {

	private AMQPChannel $channel;

	private string $exchangeName;

	/**
	 * 是否已经声明交换机
	 * @var bool
	 */
	private bool $isDeclareExchange = false;

	/**
	 * _Exchange constructor.
	 * @param com\Cla\ClaBase\DataStore $dataStore
	 * @param AMQPChannel $channel
	 * @param string $exchangeName
	 * @throws
	 */
	public function __construct( com\Cla\ClaBase\DataStore $dataStore, AMQPChannel $channel, string $exchangeName ) {
		parent::__construct( $dataStore );
		//
		$this->channel = $channel;
		//
		$this->exchangeName = $exchangeName;
	}

	/**
	 * @return AMQPChannel
	 */
	public function getChannel(  ):AMQPChannel {
		return $this->channel;
	}

	/**
	 * @return string
	 */
	public function getExchangeName(  ):string {
		return $this->exchangeName;
	}

	/**
	 * 声明交换机
	 * @param $type
	 * @param bool $passive
	 * @param bool $durable
	 * @param bool $auto_delete
	 * @param bool $internal
	 * @param bool $nowait
	 * @param array $arguments
	 * @param null $ticket
	 * @return $this
	 */
	public function exchangeDeclare(
		$type,
		$passive = false,
		$durable = false,
		$auto_delete = true,
		$internal = false,
		$nowait = false,
		$arguments = array(),
		$ticket = null
	):self {
		$this->getChannel()->exchange_declare(
			$this->exchangeName,
			$type,
			$passive,
			$durable,
			$auto_delete,
			$internal,
			$nowait,
			$arguments,
			$ticket
		);
		//
		return $this;
	}

	/**
	 * @param $data
	 * @param null $routeKey
	 * @param array $properties
	 * @return bool
	 * @throws
	 */
	public function publish( $data, $routeKey = null, array $properties = [] ):void {
		// $this->checkDeclareExchangeOrInit();
		//
		// return $this->AMQPExchange->publish( $data, $routeKey, $flags, $attributes );
		$msg = new AMQPMessage( $data, $properties );
		$this->channel->basic_publish( $msg, $this->exchangeName, $routeKey );
	}

}
